package com.colorful.insuranceproject.mine;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.base.TitleActivity;
import com.colorful.insuranceproject.bean.DeliveryBean;
import com.colorful.insuranceproject.consts.CityDataHolder;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.request.MineRequest;
import com.colorful.insuranceproject.utils.WheelActivity;
import com.lovely3x.common.utils.CommonUtils;
import com.lovely3x.common.utils.Response;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by handsome-Bob on 2017/8/21.
 * <p>
 * 添加收货地址
 */
public class AddDeliveryActivity extends TitleActivity {

    private MineRequest mineRequest;

    private static final int ADD_DELIVERY_URL = 0X1;

    public static final String ADDRESS_DETAILS = "extra_address_details";

    /**
     * 选择来自的地区的请求码
     */
    private static final int REQUEST_CODE_SELECT_FROM = 0x997;

    /**
     * 收件人姓名
     */
    @Bind(R.id.tv_addressees_name)
    EditText tvAddresseesName;

    /**
     * 联系手机
     */
    @Bind(R.id.tv_contact_phone)
    EditText tvContactPhone;

    /**
     * 所在地区
     */
    @Bind(R.id.tv_location)
    TextView tvLocation;

    /**
     * 详细地址
     */
    @Bind(R.id.tv_details_address)
    EditText tvDetailsAddress;

    /**
     * 邮政编码
     */
    @Bind(R.id.tv_post_num)
    EditText tvPostNum;

    @Bind(R.id.switch_btn)
    SwitchCompat switchBtn;

    /**
     * 保存按钮
     */
    @Bind(R.id.tv_save)
    TextView tvSave;

    //用户选择的地区

    private String areaId;

    private DeliveryBean bean;

    private String delivery;

    @Override
    protected int getContentView() {
        return R.layout.activity_add_delivery;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        setTitle(getString(R.string.add_delivery_add));
    }

    @Override
    protected void onViewInitialized() {
        mineRequest = new MineRequest(getHandler());
        if (bean != null) {
            tvAddresseesName.setText(bean.getUserName());//  收货人姓名
            tvContactPhone.setText(bean.getUserPhone());//  收货人电话
            tvDetailsAddress.setText(bean.getDetailAddress());//  收货人地址
            switchBtn.setChecked(bean.getIsDefault().equals("1"));//  设置默认
            tvLocation.setText(bean.getSimpleAddress());// 选择的地址
            areaId = bean.getAreaId();
            delivery = bean.getAddressId();
        }
    }

    @Override
    protected void onInitExtras(@NonNull Bundle bundle) {
        super.onInitExtras(bundle);
        bean = bundle.getParcelable(ADDRESS_DETAILS);
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            case ADD_DELIVERY_URL:
                tvSave.setEnabled(true);
                if (response.isSuccessful) {
                    if (bean != null) {
                        showToast(getString(R.string.modify_delivery_success));
                    } else {
                        showToast(getString(R.string.add_delivery_success));
                    }
                    setResult(RESULT_OK);
                    finish();
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;
        }
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    /**
     * 页面监听处理
     */
    @OnClick({R.id.tv_save, R.id.ll_location})
    void onClicked(View view) {
        switch (view.getId()) {
            //  判断状态
            case R.id.tv_save:
                String name = tvAddresseesName.getText().toString().trim();
                String phone = tvContactPhone.getText().toString().trim();
                String location = tvLocation.getText().toString().trim();
                String post = tvPostNum.getText().toString().trim();
                String detailsAddress = tvDetailsAddress.getText().toString().trim();
                boolean aboutBtn = switchBtn.isChecked();
                if (name.equals("") || phone.equals("") || detailsAddress.equals("") || location.equals("")) {
                    showToast(getString(R.string.please_compleate_infomation));
                } else if (!CommonUtils.isMobilePhone(phone)) {
                    showToast(getString(R.string.please_enter_the_correct_phone_number));
                } else {
                    tvSave.setEnabled(false);
                    int isDefault = (aboutBtn ? 1 : 0);
                    mineRequest.addNewShoppingAddress(delivery, name, areaId, phone, detailsAddress, isDefault, post, ADD_DELIVERY_URL);
                }
                break;

            //  选择收货地址的省市区
            case R.id.ll_location:
                WheelActivity.launchMeForResult(this, CityDataHolder.getProvince(), REQUEST_CODE_SELECT_FROM);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SELECT_FROM: {
                if (resultCode == RESULT_OK) {

                    WheelActivity.Parent parent = WheelActivity.getParentData(data);
                    WheelActivity.Middle middle = WheelActivity.getMiddleData(data);
                    WheelActivity.Child child = WheelActivity.getChildData(data);

                    StringBuilder sb = new StringBuilder();

                    if (parent != null) sb.append(parent.toString());

                    if (middle != null) sb.append(' ').append(middle.toString());

                    if (child != null) sb.append(' ').append(child.toString());
                    // 设置来自什么地方
                    tvLocation.setText(sb);
                    if (child != null) {
                        areaId = child.getId();
                    } else {
                        if (middle != null)
                            areaId = middle.getId();
                    }
                }
            }
            break;
        }
    }
}
